// Following code was adopted from Microsoft's Smart Client Offline Application Block.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace needle.Services.soab.Connectivity
{
    public class WinInetConnectionDetectionStartegy : IConnectionDetectionStrategy
    {
        [DllImport( "wininet.dll" )]
        private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue );
        
        private ConnectionState currentState;

        public WinInetConnectionDetectionStartegy()
        {
            this.currentState   = ConnectionState.Unknown;
        }

        #region IConnectionDetectionStrategy Members

        public event ConnectionStateChangedEventHandler ConnectionStateChanged;

        public bool IsConnected { get { return GetConnectionStatus(); } }

        public ConnectionState ConnectionState
        {
            get
            {
                GetConnectionStatus();
                return currentState;
            }
        }

        public bool GetConnectionStatus()
        {
            int cnxDesc = 0;
            bool retVal = InternetGetConnectedState( out cnxDesc, 0 );

            if (
                ( this.ConnectionStateChanged != null )
                &&
                ( ( retVal && currentState != ConnectionState.Online ) ||
                     ( !retVal && currentState != ConnectionState.Offline )
                )
            )
            {
                ConnectionState newState   = retVal ? ConnectionState.Online : ConnectionState.Offline;
                ConnectionState oldState   = currentState;
                currentState = newState;

                this.ConnectionStateChanged( this, new ConnectionStateChangedEventArgs( oldState, newState ) );
            }
            return retVal;
        }

        #endregion
    }
}
